<template>
  <div class="editor">
    <!-- 工具栏 -->
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="'default'"
    />
    <!-- 内容部分 -->
    <Editor
      v-model="valueHtml"
      style="height: 450px; overflow-y: hidden"
      :defaultConfig="editorConfig"
      :mode="'default'"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { imgUpload } from "@/api/sys";
import type { IEditorConfig, IToolbarConfig } from "@wangeditor/core";
const emit = defineEmits(["input"]);
const props = defineProps({
  value: {
    type: String,
    default: "",
  },
  enable: {
    type: Boolean,
    default: true,
  },
  height: {
    type: Number,
    default: 600,
  },
});
watch(
  () => props.value,
  () => {
    valueHtml = props.value;
  }
);
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  // 用于去掉不需要的工具栏配置
  excludeKeys: ["group-video", "group-more-style", "emotion"],
};
// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  // 最长输入2000字
  maxLength: 2000,
  // 进入页面不自动聚焦
  autoFocus: true,
  MENU_CONF: {},
};
// 上传图片
editorConfig.MENU_CONF["uploadImage"] = {
  async customUpload(file: File, insertFn: Function) {
    let formData = new FormData();
    formData.append("file", file);
    // 如果需要token且存在token
    let res = await imgUpload(formData);

    let path = `${import.meta.env.VITE_BASE_URL}`;
    insertFn(res, "", res);
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
function disableHandler() {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.disable();
}
let valueHtml = "";
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // 查看所有工具栏key
  // console.log(editor.getAllMenuKeys());
  if (!props.enable) {
    disableHandler();
  }
};

// 获得输入的内容
const handleChange = (editor: any) => {
  emit("input", editor.getHtml());
};
</script>

<style lang="less" scoped>
.editor {
  border: 1px solid #ccc;
  z-index: 99;
}
</style>
